package com.develope.tree.login;

import java.util.ArrayList;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import com.develope.tree.MainActivity;
import com.develope.tree.R;
import com.develope.tree.UserParcel;
import com.develope.tree.db.dbUser;
import com.develope.tree.db.dbUserParcel;
import com.develope.tree.service.HttpHandler;
import com.develope.tree.service.SoapHelper;
import com.develope.tree.utils.Alerts;
import com.develope.tree.utils.Logger;

public class LoginActivity extends Activity {

	private ArrayList<UserParcel> arrUser, arrParcel;
	public final static String EXTRA_MESSAGE = "com.develope.tree.login.LoginActivity.MESSAGE";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */

	// Values for email and password at the time of the login attempt.
	private String mUser;
	private String mPassword;
	dbUserParcel parceldb;
	dbUser userdb;
	// UI references.
	private EditText mUserView;
	private EditText mPasswordView;
	private User user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.

		mUserView = (EditText) findViewById(R.id.user);

		mPasswordView = (EditText) findViewById(R.id.password);

		userdb = new dbUser(this);
		userdb.getWritableDatabase();
		parceldb = new dbUserParcel(this);
		parceldb.getWritableDatabase();

		User user1 = new User();
		user1.setUser("admin");
		user1.setPass("123456");
//		userdb.insertUser(user1);

		User user2 = new User();
		user2.setUser("khangcuong");
		user2.setPass("123456");
//		userdb.insertUser(user2);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						mUser = mUserView.getText().toString();
						mPassword = mPasswordView.getText().toString();
						
						user = new User();
						user.setUser(mUser);
						user.setPass(mPassword);
						
						if (!isNetworkAvailable()) {
							loginOffline(user);

						} else
							loginOffline(user);	
//						attemptLogin(user);
					}

				});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	private void loginOffline(User user) {
		// TODO Auto-generated method stub

		mUserView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		

		// sampleCallSOAP();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		boolean b = true;
		
//		if (userdb.checkLogin(user)) {
		if (b){
			sampleCallSOAP(mUser);
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				intent.putExtra(EXTRA_MESSAGE, mUser);
				startActivity(intent);
			} else {
				Alerts.showNotifyDialog(LoginActivity.this,
						"UserName or Password is incorrect! Please try again");
				focusView = mUserView;
				focusView.requestFocus();
				return;
			}
		
	}

	public void attemptLogin(final User user) {

		// Reset errors.
		mUserView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			PropertyInfo[] proInfos = new PropertyInfo[2];
			PropertyInfo proInfo = new PropertyInfo();
			proInfo.setName("username");
			proInfo.setValue(user.getUser());
			proInfo.setType(String.class);
			proInfos[0] = proInfo;
			proInfo = new PropertyInfo();
			proInfo.setName("pass");
			proInfo.setValue(user.getPass());
			proInfo.setType(String.class);
			proInfos[1] = proInfo;
/*
			HttpHandler httpHandlerCheckUser = new HttpHandler(
					SoapHelper.METHOD_CHECK_USER, proInfos) {
				@Override
				public void onResponse(int errorCode, String result) {
					View focusView = null;
					mUser = mUserView.getText().toString();
					mPassword = mPasswordView.getText().toString();
					
					Alerts.hideLoadingDialog();
					Logger.error("[onResponse] errorCode:" + errorCode + " \n "
							+ result);

					if (TextUtils.isEmpty(result)) {
						Alerts.showButtonDialog(LoginActivity.this,
								"Login Failed! Please try again.", null);
						return;
					}

					switch (result) {
					case "True":

						mUser = mUserView.getText().toString();
						mPassword = mPasswordView.getText().toString();
						
						userdb.updateUser(user);
						sampleCallSOAP(mUser);
						
						Intent intent = new Intent(LoginActivity.this,
								MainActivity.class);
						intent.putExtra(EXTRA_MESSAGE, mUser);
						startActivity(intent);
						return;

					case "False":
						Alerts.showNotifyDialog(LoginActivity.this,
								"UserName or Password is incorrect! Please try again");
						focusView = mUserView;
						focusView.requestFocus();
						return;
					}
				}

			};

			httpHandlerCheckUser.execute();

	*/	}
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	private void sampleCallSOAP(final String mUser) {

		PropertyInfo proInfo = new PropertyInfo();
		proInfo.setName("UserName");
		proInfo.setValue(mUser);
		proInfo.setType(String.class);

		HttpHandler httpHandler = new HttpHandler(
				SoapHelper.METHOD_GetUserParcels, proInfo) {

			@Override
			public void onResponse(int errorCode, String result) {

				arrUser = new ArrayList<UserParcel>();
				Alerts.hideLoadingDialog();
				Logger.error("[onResponse] errorCode:" + errorCode);

				if (TextUtils.isEmpty(result) || !result.contains(";")) {
					Log.d("Error! ", "Khong the get Parcel");
					return;
				}
				String[] rows = result.split(";");
				// thieu check null truoc khi su dung, neu khong app se bi crash
				// do nullPointerException
				// should add code
				if (rows == null)
					return;
				
				for (int i = 0; i < rows.length; i++) {
					String[] cols = rows[i].split(":");
					UserParcel up = new UserParcel();
					up.setParcelID(Integer.parseInt(cols[0]));
					up.setParcelName(cols[1].toString());
					up.setUserName(mUser);
					parceldb.comPare1(up);
					arrUser.add(up);
				}
				parceldb.comPare2(arrUser, mUser);
			}
		};
		// ktra network truoc khi goi API
		if (isNetworkAvailable()) {
			// show progress dialog
			Alerts.showLoadingDialog(this, null, null);
			httpHandler.execute();
			return;
		}
	}

}
